merkle-lib
A performance conscious library for merkle root and tree calculations.
NOTE: As is, this implementation is vulnerable to a forgery attack (as a second pre-image attack), see these[1][2] crypto.stackexchange questions for an explanation.
To avoid this vulnerability, you should pre-hash your leaves using a different hash function than the function provided such that H(x) != H'(x)
.
Examples
Preamble
var crypto = require('crypto')
function sha256 (data) {
return crypto.createHash('sha256').update(data).digest()
}
var data = [
'cafebeef',
'ffffffff',
'aaaaaaaa',
'bbbbbbbb',
'cccccccc'
].map(x => new Buffer(x, 'hex'))
// ... now, the examples
Tree
var merkle = require('merkle-lib')
var tree = merkle(data, sha256)
console.log(tree.map(x => x.toString('hex')))
Root only (equivalent to tree[tree.length - 1]
)
var fastRoot = require('merkle-lib/fastRoot')
var root = fastRoot(data, sha256)
console.log(root.toString('hex'))
Proof (with verify)
var merkleProof = require('merkle-lib/proof')
var proof = merkleProof(tree, data[0])
if (proof === null) {
console.error('No proof exists!')
}
console.log(proof.map(x => x && x.toString('hex')))
console.log(merkleProof.verify(proof, sha256))
Credits
Thanks to Meni Rosenfield on bitcointalk for the math.